import axios from 'axios'
import mpAdapter from 'axios-miniprogram-adapter'
import {
  API_URL
} from '@/config/api'
import useUserStore from '@/store/user'
import {
  toast
} from '@/utils/uni-app'
import {
  useSign
} from './request-sign'
import {
  jump
} from './router'

axios.defaults.adapter = mpAdapter
const service = axios.create({
  baseURL: API_URL,
  timeout: 60 * 1000,
  headers: {
    business: 'bcwWeChat'
  }
})

service.interceptors.request.use(
  config => {
    const {
      token
    } = useUserStore()
    if (token) config.headers.token = token

    useSign(config)

    return config
  },
  error => {
    console.log('request interceptors error: ', error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    let {
      code,
      data,
      msg
    } = response.data

    /**
     * 200=成功
     * 401=登录失效
     * 40013=未注册
     */

    const userStore = useUserStore()
    if ([201].includes(code)) return Promise.resolve(response.data) // 首页接口如果code是201则再次调用

    if ([555].includes(code)) {
      toast.info(msg)
      jump('/pages/main/home/index')
    }

    if ([200, 40013].includes(code)) return Promise.resolve(data)

    if ([40022].includes(code)) {
      userStore.logout()
    }
    if ([401].includes(code)) {
      userStore.logout()

      setTimeout(() => {
        userStore.setLoginToast(true)
        jump('/pages/main/user/index')
      }, 1000)
    }

    if (/Internal Server Error/g.test(msg)) msg = '服务器异常，请稍后再试'

    console.log(response)
    const {
      hideNotify
    } = response.config!hideNotify && toast.info(msg || '未知错误')

    return Promise.reject(response.data)
  },
  error => {
    console.log('response interceptors error: ', error)

    if (error.message === 'timeout [ 10000ms ]') {
      error.message = '连接超时'
    }

    toast.error(error.message)

    return Promise.reject(error)
  }
)

export default service